package m.store.service;

import com.alibaba.fastjson.JSONObject;
import m.base.util.PowerUtil;
import m.common.model.util.*;
import m.common.service.Service;
import m.store.model.*;
import m.store.task.*;
import m.system.db.TransactionManager;
import m.system.exception.MException;
import m.system.util.DateUtil;
import m.system.util.GenerateID;
import m.system.util.NumberUtil;

import java.util.Date;

public class GoodsOutRecordService extends Service {
    public void saveRefund(GoodsOutRecord model) throws Exception {
        TransactionManager tm=new TransactionManager();
        try {
            tm.begin();
            ModelQueryCheck.init(SaleInfo.class, model.getBackRecord().getSale().getOid())
                    .checkStrEq("status", OrderModel.Status_Done, "订单审核通过后才能录入退货")
                    .checkStrEq("inputUser.oid", PowerUtil.getSessionUserOid(), "只有录入人才能录入退货")
                    .doCheck(false, true);
            ModelQueryCheck.init(model)
                    .checkNotNull("backRecord.oid", "参数错误")
                    .checkNotNull("num", "请输入退货数量")
                    .checkNumberRange("num", 1D, 99999999D, "退货数量不能小于1")
                    .checkNotNull("price", "请输入退货单价")
                    .checkNumberRange("price", 0D, 99999999D, "退货单价不能小于0")
                    .doCheck(false, true);
            model.setBackRecord(ModelQueryList.getModel(model.getBackRecord(), "*", "sale.*", "record.*"));
            if (model.getNum() > model.getBackRecord().getSurplusNum()) {
                throw new MException(this.getClass(), "退货数量不能超过" + model.getBackRecord().getSurplusNum());
            }
            model.setGoods(model.getBackRecord().getGoods());
            model.setRecord(model.getBackRecord().getRecord());
            model.setStore(model.getBackRecord().getStore());
            model.setSale(model.getBackRecord().getSale());
            model.setOperDate(new Date());
            model.setNum(-model.getNum());
            model.setPreferential(0d);
            model.setPreferentialPrice(model.getPrice());
            model.setSaleAmount(NumberUtil.round(model.getNum() * model.getPrice(), 2));
            model.setStockPrice(model.getRecord().getPreferentialPrice());
            model.setGainAmount(NumberUtil.round((model.getPrice() - model.getStockPrice()) * model.getNum(), 2));
            model.setOid(GenerateID.generatePrimaryKey());
            ModelUpdateUtil.insertModel(model);
            getService(GoodsRecordNoticeService.class).insertNotice(model, GoodsRecordNotice.Type_Refund_Sale);
            getService(SaleInfoService.class).updateAmount(model.getSale().getOid(), model.getSale().getStore().getOid(),model.getSale().getGuest().getOid());
            tm.commit();
        }catch(Exception e){
            tm.rollback();
            throw e;
        }
        //更新冗余信息
        GoodsOutRecordSupport.add(model.getBackRecord().getOid(),model.getSale().getOid(),model.getGoods().getOid());
        GoodsOutRecordSupport.start();
        StoreGoodsSupport.doneHandler(model.getGoods().getOid());
        GoodsStockRecordSupport.add(model.getRecord().getOid(),model.getRecord().getStock().getOid(),model.getGoods().getOid());
        GoodsStockRecordSupport.start();
        //更新客户出库金额
        GuestSaleSupport.add(model.getSale().getGuest().getOid());
        GuestSaleSupport.start();
        //更新月度统计
        MonthRecordSupport.add(model.getSale().getInputUser().getOid(),model.getSale().getSaleDate(), MonthRecord.Type_Sale);
        MonthRecordSupport.start();
    }
    public void deleteRefund(String oid) throws Exception {
        GoodsOutRecord model = ModelQueryList.getModel(GoodsOutRecord.class, oid, "*", "sale.*", "record.surplusNum", "backRecord.surplusNum", "record.stock.oid");
        TransactionManager tm=new TransactionManager();
        try {
            tm.begin();
            if (!DateUtil.format(new Date(), "yyyyMM").equals(DateUtil.format(model.getOperDate(), "yyyyMM"))) {
                throw new MException(this.getClass(), "无法删除跨月操作的数据");
            }
            if (-model.getNum() > model.getRecord().getSurplusNum()) {
                throw new MException(this.getClass(), "库存商品不足，无法删除退货");
            }
            if (!getService(GoodsRecordNoticeService.class).removeNotice(model))
                throw new MException(this.getClass(), "退货通知已阅，无法删除。");
            ModelUpdateUtil.deleteModel(model);
            getService(SaleInfoService.class).updateAmount(model.getSale().getOid(), model.getSale().getStore().getOid(),model.getSale().getGuest().getOid());
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw e;
        }
        //更新冗余信息
        GoodsOutRecordSupport.add(model.getBackRecord().getOid(),model.getSale().getOid(),model.getGoods().getOid());
        GoodsOutRecordSupport.start();
        StoreGoodsSupport.doneHandler(model.getGoods().getOid());
        GoodsStockRecordSupport.add(model.getRecord().getOid(),model.getRecord().getStock().getOid(),model.getGoods().getOid());
        GoodsStockRecordSupport.start();
        //更新客户出库金额
        GuestSaleSupport.add(model.getSale().getGuest().getOid());
        GuestSaleSupport.start();
        //更新月度统计
        MonthRecordSupport.add(model.getSale().getInputUser().getOid(),model.getSale().getSaleDate(),MonthRecord.Type_Sale);
        MonthRecordSupport.start();
    }
}
